package com.iMusic.businessLogicLayer;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import com.iMusic.integrationLayer.DBConnection;
import com.iMusic.integrationLayer.DBConnectionManager;
import com.iMusic.util.Parameters;

public class ShippingManager {

	HashMap<Long,Float> shipRates = null;
	
	static final Long WITHIN_PROVINCE = (long) 1;
	static final Long WITHIN_COUNTRY = (long) 2;
	static final Long INTERNATIONAL = (long) 3;
	
	
	static private ShippingManager shipMgr = null;

	/*
	 * Constructor
	 */
	private ShippingManager() {
		shipRates = new HashMap<Long,Float>();
		loadShippingRates();
	}
	
	/*
	 * Get shipping manager instance
	 */
	static public ShippingManager getInstance() {
		if (shipMgr == null) {
			shipMgr = new ShippingManager();
		}
		return shipMgr;
	}
	
	/*
	 * Loads shipping rates
	 */
	public void loadShippingRates() {
		DBConnectionManager dbConnMgr = DBConnectionManager.getDBConnectionManager();
		DBConnection dbConn = dbConnMgr.getDBConnection();
		
		dbConn.connect();
		
		String stmt = "SELECT TYPE, DESCRIPTION, PRICE, S.EffectiveDate " +
						"FROM SHIPPING S " +
						"HAVING S.EffectiveDate IN (SELECT MAX(S2.EFFECTIVEDATE) FROM SHIPPING S2 WHERE S.TYPE = S2.TYPE)";
		ResultSet rs = dbConn.query(stmt);
		System.out.println(stmt);
		
		if (shipRates == null) {
			shipRates = new HashMap<Long, Float>();
		}

		try {

			while (rs != null && rs.next()) {
				shipRates.put(rs.getLong("TYPE"), rs.getFloat("PRICE"))	;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		dbConn.disconnect();
		dbConnMgr.freeDBConnection(dbConn);
	}
	
	/*
	 * Returns the shipping rate per type
	 */
	public float getShippingRate(String country, String province) {
		float rate = 0;
		
		if (!country.equals(Parameters.HOME_COUNTRY)) {
			// International
			rate = shipRates.get(INTERNATIONAL);
		}
		else if (!province.equals(Parameters.HOME_PROVINCE)) {
			// outside home province
			rate = shipRates.get(WITHIN_COUNTRY);			
		}
		else {
			// inside home province
			rate = shipRates.get(WITHIN_PROVINCE);			
		}
		
		return rate;
	}

	/*
	 * Returns the shipping rate per type
	 */
	public long getShippingType(String country, String province) {
		long ret = 0;
		
		if (!country.equals(Parameters.HOME_COUNTRY)) {
			// International
			ret = INTERNATIONAL;
		}
		else if (!province.equals(Parameters.HOME_PROVINCE)) {
			// outside home province
			ret = WITHIN_COUNTRY;			
		}
		else {
			// inside home province
			ret = WITHIN_PROVINCE;			
		}
		
		return ret;
	}
	
	
}
